package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.ImageGridAdapter2;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LePhotoItemWrapper;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PhotoItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoai.pulltorefresh.PullableGridView;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.IntentConstants;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;


/**
 * 专业测试题
 * 
 * @author hf
 * 
 */
@SuppressLint({ "ShowToast", "InflateParams" })
public class SchoolAlbumActivity extends BaseActivity implements
    OnClickListener {

//  @InjectView(id = R.id.testprogress)
//  private ProgressBar progressBar;
//  @InjectView(id = R.id.titlelyt)
//  private LinearLayout titlelyt;
//  @InjectView(id = R.id.layout_test)
//  private LinearLayout layout_test;

  private ArrayList<PhotoItem> mRadioAdapterList;
  private ArrayList<PhotoItem> mRadioArrayList;

  public boolean isrefreshlist2 = false;

  private LePhotoItemWrapper /*mLeFavoriteItemWrapper1,*/
          mLeFavoriteItemWrapper2;

  private ImageGridAdapter2 mRadioAdapter;


  private void fillPhotoList(boolean loadFail) {
    if (mRadioAdapter == null) {
      if (mRadioArrayList != null && !mRadioArrayList.isEmpty()) {
        mRadioAdapter = new ImageGridAdapter2(this, mRadioArrayList);
      } else {
        mRadioAdapter = new ImageGridAdapter2(this,
                new ArrayList<PhotoItem>());
      }

      listView2.setAdapter(mRadioAdapter);
    } else {
      mRadioAdapter.notifyDataSetChanged();

      if (mRadioArrayList != null
              && mRadioArrayList.size() == mLeFavoriteItemWrapper2.total) {
        refreshLayout2.refreshFinish(PullToRefreshLayout.LOAD_COMPLETED);
        refreshLayout2.loadmoreFinish(PullToRefreshLayout.LOAD_COMPLETED);
      } else {
        refreshLayout2.refreshFinish(PullToRefreshLayout.SUCCEED);
        refreshLayout2.loadmoreFinish(PullToRefreshLayout.SUCCEED);
      }

      // refreshLayout2.refreshFinish(PullToRefreshLayout.SUCCEED);
      // refreshLayout2.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    if (loadFail) {
      emptylayout2.setVisibility(View.VISIBLE);
      btnReload2.setVisibility(View.VISIBLE);
      img_defaultfail2.setBackgroundResource(R.drawable.defailt_fail);
    } else {
      if (mRadioAdapter.getCount() == 0) {
        emptylayout2.setVisibility(View.VISIBLE);
        btnReload2.setVisibility(View.GONE);
        img_defaultfail2.setBackgroundResource(R.drawable.empty_mylove);
      } else {
        emptylayout2.setVisibility(View.GONE);
      }
    }
  }

  private void loadPhotoData() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
          if (mRadioAdapterList != null) {
            mRadioAdapterList.clear();
          }
          if (isrefreshlist2) {
            mRadioArrayList.clear();
          }

          mLeFavoriteItemWrapper2 = JsonSerializer.getInstance().deserialize(
                  result.data, LePhotoItemWrapper.class);
          mRadioAdapterList = (ArrayList<PhotoItem>) mLeFavoriteItemWrapper2.data;
          if (Tools.isNotEmpty(mRadioAdapterList)) {
            mRadioArrayList.addAll(mRadioAdapterList);
          }

          fillPhotoList(false);
        } else {
          mRadioArrayList.clear();
          fillPhotoList(true);
        }

        isrefreshlist2 = false;
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

        param_.put(HttpUtils.TAG_PAGE_I, mLastpage2);
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        param_.put("page_size", 9);
        return HttpUtils.startRequest(HttpUtils.API_URL
                        + "/api/2.0/teacher/teacher_photo/child_get", param_,
                HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private int mLastpage2 = 1;

  private LinearLayout emptylayout2;
  private RippleView reloadRippleView2;
  private PullToRefreshLayout refreshLayout2;
  private PullableGridView listView2;
  private ImageView img_defaultfail2;
  private Button btnReload2;


    @InjectView(id = R.id.bottomlyt)
    private LinearLayout bottomlyts;
    @InjectView(id = R.id.delete, click = true)
    private Button delete;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.schoolalbum);

    setTitle("校园成长相册");

      mTvUpright.setTextColor(0xffffffff);
      mTvUpright.setVisibility(View.VISIBLE);
      mTvUpright.setText("编辑");


      mTvUpright.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
              if (!bottomlyts.isShown()) {
                  bottomlyts.setVisibility(View.VISIBLE);
                  mTvUpright.setText("取消");

                  if (mRadioAdapter != null) {
                      mRadioAdapter.setEditable(true);
                      mRadioAdapter.notifyDataSetChanged();
                  }
              } else {
                  bottomlyts.setVisibility(View.GONE);

                  if (mRadioAdapter != null) {
                      mRadioAdapter.setEditable(false);

                      if (mRadioArrayList != null) {
                          for (PhotoItem item : mRadioArrayList) {
                              item.isChecked = false;
                          }
                      }

                      mRadioAdapter.notifyDataSetChanged();
                  }

                  mTvUpright.setText("编辑");
              }
          }
      });

      findViewById(R.id.delete).setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    mRadioAdapterList = new ArrayList<>();
    mRadioArrayList = new ArrayList<>();

    emptylayout2 = (LinearLayout) findViewById(R.id.emptylayout);
    reloadRippleView2 = (RippleView) findViewById(R.id.reloadRippleView);
    refreshLayout2 = (PullToRefreshLayout) findViewById(R.id.refresh_view);
    listView2 = (PullableGridView) findViewById(R.id.content_views);
    img_defaultfail2 = (ImageView) findViewById(R.id.img_defaultfail);
    btnReload2 = (Button) findViewById(R.id.reload);

    refreshLayout2.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
      @Override
      public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mLastpage2 = 1;
        isrefreshlist2 = true;
        loadPhotoData();
        //  loadRadioData();
      }

      @Override
      public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        mLastpage2++;
        isrefreshlist2 = false;
        loadPhotoData();
        //  loadRadioData();
      }
    });

    reloadRippleView2
            .setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
              @Override
              public void onComplete(RippleView rippleView) {
                mLastpage2 = 1;
                isrefreshlist2 = true;
                loadPhotoData();
              }
            });

//    listView2.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//      @Override
//      public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//        PhotoItem item = mRadioArrayList.get(position);
//        if (item.isChecked) {
//          item.isChecked = false;
//          selectedImgs.remove(item.id);
//        } else {
////                        if (selectedImgs.size() >= availableSize) {
////                            Toast.makeText(ImageChooseActivity.this,
////                                    "最多选择" + availableSize + "张图片", Toast.LENGTH_SHORT).show();
////                            return;
////                        }
//          item.isChecked = true;
//          selectedImgs.put(item.id, item);
//        }
//
//        mRadioAdapter.notifyDataSetChanged();
//
//        return true;
//      }
//    });

    listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                              long arg3) {




        if (!bottomlyts.isShown()) {
            Intent intent = new Intent(SchoolAlbumActivity.this,
                    ImageZoomActivity2.class);
            intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST, mRadioArrayList);
            intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, arg2);
            startActivity(intent);
        } else {
          PhotoItem item = mRadioArrayList.get(arg2);
          if (item.isChecked) {
            item.isChecked = false;
            selectedImgs.remove(item.id);
          } else {
//                        if (selectedImgs.size() >= availableSize) {
//                            Toast.makeText(ImageChooseActivity.this,
//                                    "最多选择" + availableSize + "张图片", Toast.LENGTH_SHORT).show();
//                            return;
//                        }
            item.isChecked = true;
            selectedImgs.put(item.id, item);
          }

          mRadioAdapter.notifyDataSetChanged();
        }




//                Intent intent = new Intent();
//                intent.setClass(MyLoveListActivity.this, StoryDetailActivity.class);
////                intent.putExtra("id", mRadioArrayList.get(arg2).episode.album_id);
////                intent.putExtra("sort", mRadioArrayList.get(arg2).episode.sort); // 第几集，高亮
//                startActivity(intent);
      }
    });

    loadPhotoData();
  }

  private HashMap<Integer, PhotoItem> selectedImgs = new HashMap<Integer, PhotoItem>();


  @Override
  protected void onDestroy() {
    super.onDestroy();

  }

    private void deleteRadio() {
        int selectCount = 0;
        if (mRadioArrayList != null) {
            for (PhotoItem item : mRadioArrayList) {
                if (item != null && item.isChecked) {
                    ++selectCount;
                }
            }
        }

        if (selectCount > 0) {
            CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
                    SchoolAlbumActivity.this).setMessage("确定删除吗？").setTitle("删除提示")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {

                            if (mRadioArrayList != null && !mRadioArrayList.isEmpty()) {
                                final List<PhotoItem> selectedRecordings = new ArrayList<PhotoItem>();
                                String storyIds = "";

                                for (PhotoItem item : mRadioArrayList) {
                                    if (item.isChecked) {
                                        selectedRecordings.add(item);
                                        storyIds += item.id;
                                        storyIds += ",";
                                    }
                                }

                                if (Tools.isNotEmpty(storyIds)) {
                                    storyIds = storyIds.substring(0, storyIds.length() - 1);
                                }

                                if (selectedRecordings.size() > 0) {
                                    showloading("");
                                    final String finalStoryIds = storyIds;
                                    new CustomAsyncTask(SchoolAlbumActivity.this,
                                            new IAsyncTask() {
                                                @Override
                                                public void onRecieveData(Activity activity,
                                                                          ResponseResult result) {

                                                    if (result != null && result.isSuccess()) {
                                                        for (PhotoItem rItem : selectedRecordings) {
                                                            mRadioAdapter.remove(rItem);
                                                        }
                                                        mRadioAdapter.removeSelection();

                                                        if (Tools.isNotNullStr(result.data)) {
                                                            Toast.makeText(SchoolAlbumActivity.this,
                                                                    "删除成功!", Toast.LENGTH_SHORT).show();
                                                        }
                                                    }

                                                    dismissLoading();
                                                }

                                                @Override
                                                public ResponseResult doInbackground(Activity activity) {
                                                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                                                    if (lu == null) {
                                                        lu = Tools.restoreLeUser();
                                                    }

                                                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                                                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                                                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                                                    return HttpUtils.startRequest(HttpUtils.HOST_API
                                                                    + "/api/2.0/teacher/teacher_photo/child_delete/" + finalStoryIds,
                                                            param_, HttpUtils.TAG_DELETE_REQUEST);
                                                }
                                            }).execute();

                                }
                                dialog.dismiss();
                            }
                        }
                    });
            cdb.create().show();
        } else {
            toastShow("未选中任何条目!");
        }
    }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
//        case R.id.tv_edittt:
//
//            break;
        case R.id.delete:
            deleteRadio();
    default:
      break;
    }
  }


}
